<?php

namespace app\admin\model\workorder;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Category extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'workorder_category';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'wo_number'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    public function getWoNumberAttr($value, $data)
    {
        $woNumber = [
            'number'          => 0,
            'complete_number' => 0
        ];

        if ($data['pid'] == 0) {
            $category_ids = Db::name('workorder_category')->where('pid', $data['id'])->column('id');
            foreach ($category_ids as $category_id) {
                $woNumber['number']          += Orders::where('category_id', $category_id)->count('id');
                $woNumber['complete_number'] += Orders::where('category_id', $category_id)
                    ->where('status', '>=', 4)
                    ->count('id');
            }
        } else {
            $woNumber['number']          = Orders::where('category_id', $data['id'])->count('id');
            $woNumber['complete_number'] += Orders::where('category_id', $data['id'])
                ->where('status', '>=', 4)
                ->count('id');
        }
        return $woNumber;
    }


    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list  = $this->getStatusList();
        return $list[$value] ?? '';
    }
}
